package com.farmer.consultation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.farmer.common.entity.ConsultationQa;
import com.farmer.common.result.Result;
import com.farmer.consultation.mapper.ConsultationMapper;
import com.farmer.consultation.service.ConsultationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 咨询问答服务实现类
 */
@Slf4j
@Service
public class ConsultationServiceImpl implements ConsultationService {

    @Autowired
    private ConsultationMapper consultationMapper;

    @Override
    public Result<?> getConsultationList(Integer pageNum, Integer pageSize, String category, String questionStatus, Integer isPublic, String keyword) {
        try {
            Page<ConsultationQa> page = new Page<>(pageNum, pageSize);
            QueryWrapper<ConsultationQa> queryWrapper = new QueryWrapper<>();

            if (StringUtils.hasText(category)) {
                queryWrapper.eq("category", category);
            }
            if (StringUtils.hasText(questionStatus)) {
                queryWrapper.eq("question_status", questionStatus);
            }
            if (isPublic != null) {
                queryWrapper.eq("is_public", isPublic);
            }
            if (StringUtils.hasText(keyword)) {
                queryWrapper.and(wrapper -> wrapper
                    .like("title", keyword)
                    .or()
                    .like("question_content", keyword)
                );
            }

            queryWrapper.orderByDesc("question_time");
            Page<ConsultationQa> consultationPage = consultationMapper.selectPage(page, queryWrapper);

            Map<String, Object> result = new HashMap<>();
            result.put("records", consultationPage.getRecords());
            result.put("total", consultationPage.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);

            return Result.success("获取咨询问答列表成功", result);
        } catch (Exception e) {
            log.error("获取咨询问答列表失败：{}", e.getMessage(), e);
            return Result.error("获取咨询问答列表失败");
        }
    }

    @Override
    public Result<?> getConsultationById(Long consultationId) {
        try {
            ConsultationQa consultation = consultationMapper.selectById(consultationId);
            if (consultation == null) {
                return Result.error("咨询记录不存在");
            }
            return Result.success("获取咨询详情成功", consultation);
        } catch (Exception e) {
            log.error("获取咨询详情失败：{}", e.getMessage(), e);
            return Result.error("获取咨询详情失败");
        }
    }

    @Override
    public Result<?> submitQuestion(ConsultationQa consultation) {
        try {
            if (!StringUtils.hasText(consultation.getTitle())) {
                return Result.error("问题标题不能为空");
            }

            consultation.setQuestionNo("Q" + System.currentTimeMillis());
            consultation.setQuestionStatus("PENDING");
            consultation.setQuestionTime(LocalDateTime.now());
            consultation.setViewCount(0);
            consultation.setLikeCount(0);

            int result = consultationMapper.insert(consultation);
            if (result > 0) {
                return Result.success("提交咨询问题成功", consultation);
            } else {
                return Result.error("提交咨询问题失败");
            }
        } catch (Exception e) {
            log.error("提交咨询问题失败：{}", e.getMessage(), e);
            return Result.error("提交咨询问题失败");
        }
    }

    @Override
    public Result<?> answerQuestion(Long consultationId, String answerContent, String answerImages) {
        try {
            ConsultationQa consultation = consultationMapper.selectById(consultationId);
            if (consultation == null) {
                return Result.error("咨询记录不存在");
            }

            consultation.setAnswerContent(answerContent);
            consultation.setAnswerImages(answerImages);
            consultation.setAnswerTime(LocalDateTime.now());
            consultation.setQuestionStatus("ANSWERED");

            int result = consultationMapper.updateById(consultation);
            if (result > 0) {
                return Result.success("回答问题成功");
            } else {
                return Result.error("回答问题失败");
            }
        } catch (Exception e) {
            log.error("回答问题失败：{}", e.getMessage(), e);
            return Result.error("回答问题失败");
        }
    }

    @Override
    public Result<?> updateQuestionStatus(Long consultationId, String status) {
        try {
            ConsultationQa consultation = consultationMapper.selectById(consultationId);
            if (consultation == null) {
                return Result.error("咨询记录不存在");
            }

            consultation.setQuestionStatus(status);
            int result = consultationMapper.updateById(consultation);
            return result > 0 ? Result.success("更新状态成功") : Result.error("更新状态失败");
        } catch (Exception e) {
            log.error("更新问题状态失败：{}", e.getMessage(), e);
            return Result.error("更新问题状态失败");
        }
    }

    @Override
    public Result<?> getUserConsultations(Long userId, Integer pageNum, Integer pageSize) {
        try {
            Page<ConsultationQa> page = new Page<>(pageNum, pageSize);
            QueryWrapper<ConsultationQa> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId).orderByDesc("question_time");

            Page<ConsultationQa> consultationPage = consultationMapper.selectPage(page, queryWrapper);

            Map<String, Object> result = new HashMap<>();
            result.put("records", consultationPage.getRecords());
            result.put("total", consultationPage.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);

            return Result.success("获取用户咨询记录成功", result);
        } catch (Exception e) {
            log.error("获取用户咨询记录失败：{}", e.getMessage(), e);
            return Result.error("获取用户咨询记录失败");
        }
    }

    @Override
    public Result<?> getExpertAnswers(Long expertId, Integer pageNum, Integer pageSize) {
        try {
            Page<ConsultationQa> page = new Page<>(pageNum, pageSize);
            QueryWrapper<ConsultationQa> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("expert_id", expertId).orderByDesc("answer_time");

            Page<ConsultationQa> consultationPage = consultationMapper.selectPage(page, queryWrapper);

            Map<String, Object> result = new HashMap<>();
            result.put("records", consultationPage.getRecords());
            result.put("total", consultationPage.getTotal());

            return Result.success("获取专家回答记录成功", result);
        } catch (Exception e) {
            log.error("获取专家回答记录失败：{}", e.getMessage(), e);
            return Result.error("获取专家回答记录失败");
        }
    }

    @Override
    public Result<?> increaseViewCount(Long consultationId) {
        try {
            ConsultationQa consultation = consultationMapper.selectById(consultationId);
            if (consultation != null) {
                consultation.setViewCount(consultation.getViewCount() + 1);
                consultationMapper.updateById(consultation);
            }
            return Result.success("增加浏览次数成功");
        } catch (Exception e) {
            log.error("增加浏览次数失败：{}", e.getMessage(), e);
            return Result.error("增加浏览次数失败");
        }
    }

    @Override
    public Result<?> toggleLike(Long consultationId, Boolean isLike) {
        try {
            ConsultationQa consultation = consultationMapper.selectById(consultationId);
            if (consultation != null) {
                int change = isLike ? 1 : -1;
                consultation.setLikeCount(Math.max(0, consultation.getLikeCount() + change));
                consultationMapper.updateById(consultation);
            }
            return Result.success("操作成功");
        } catch (Exception e) {
            log.error("点赞操作失败：{}", e.getMessage(), e);
            return Result.error("点赞操作失败");
        }
    }

    @Override
    public Result<?> rateConsultation(Long consultationId, Integer satisfaction) {
        try {
            ConsultationQa consultation = consultationMapper.selectById(consultationId);
            if (consultation == null) {
                return Result.error("咨询记录不存在");
            }

            consultation.setUserSatisfaction(satisfaction);
            consultationMapper.updateById(consultation);
            return Result.success("评价成功");
        } catch (Exception e) {
            log.error("评价咨询服务失败：{}", e.getMessage(), e);
            return Result.error("评价咨询服务失败");
        }
    }

    @Override
    public Result<?> getFeaturedQaList(Integer limit) {
        try {
            QueryWrapper<ConsultationQa> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_featured", 1)
                       .eq("question_status", "ANSWERED")
                       .orderByDesc("like_count", "view_count")
                       .last("LIMIT " + (limit != null ? limit : 10));

            List<ConsultationQa> qaList = consultationMapper.selectList(queryWrapper);
            return Result.success("获取精选问答成功", qaList);
        } catch (Exception e) {
            log.error("获取精选问答失败：{}", e.getMessage(), e);
            return Result.error("获取精选问答失败");
        }
    }

    @Override
    public Result<?> getConsultationStatistics() {
        try {
            QueryWrapper<ConsultationQa> queryWrapper = new QueryWrapper<>();
            Long totalQuestions = consultationMapper.selectCount(queryWrapper);

            queryWrapper.clear();
            queryWrapper.eq("question_status", "ANSWERED");
            Long answeredQuestions = consultationMapper.selectCount(queryWrapper);

            queryWrapper.clear();
            queryWrapper.eq("question_status", "PENDING");
            Long pendingQuestions = consultationMapper.selectCount(queryWrapper);

            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalQuestions", totalQuestions);
            statistics.put("answeredQuestions", answeredQuestions);
            statistics.put("pendingQuestions", pendingQuestions);

            return Result.success("获取咨询统计信息成功", statistics);
        } catch (Exception e) {
            log.error("获取咨询统计信息失败：{}", e.getMessage(), e);
            return Result.error("获取咨询统计信息失败");
        }
    }
} 